//接收数据函数
#include "recivedata.h"
#include"Buffer.h"
#include<iostream>
#include"clientSock.h"
#include<QDebug>
#include"mainwindow.h"

#define MAXDATASIZE 8192

ReceiveData::ReceiveData()
{
}

ReceiveData &ReceiveData::getInstance()
{
    static ReceiveData instace;
    return  instace;
}

void ReceiveData::reviveData()
{
    char buff[MAXDATASIZE] = {0};
    int clnt_fd = Client::getInstance().getSockfd();

    while (!stopFlag) {
        ssize_t size = recv(clnt_fd, buff, sizeof(buff)-1, 0);
        if (size > 0) {
            accumulatedBuffer.append(buff, size);  // 追加到累积缓冲区
            // 循环处理所有可能的完整数据包
            while (static_cast<uint32_t>(accumulatedBuffer.BuffSize()) >= sizeof(CloudDrive::PacketHeader)) {
                // 先解析头部获取完整长度
                CloudDrive::PacketHeader header;
                memcpy(&header, accumulatedBuffer.c_str(), sizeof(header));

                // 检查缓冲区是否包含完整数据包
                if (static_cast<uint32_t>(accumulatedBuffer.BuffSize()) >= header.length) {
                    // 创建临时缓冲区保存完整数据包
                    Buffer packetBuffer;
                    packetBuffer.append(accumulatedBuffer.c_str(), header.length);

                    // 处理完整数据包
                    handleEvent(packetBuffer);

                    // 从累积缓冲区移除已处理数据
                    accumulatedBuffer.BuffetClear();  // 清空当前缓冲区
                    if (header.length < static_cast<uint32_t>(accumulatedBuffer.BuffSize())) {
                        // 如果有剩余数据，移动到缓冲区开始
                        const char* remainingData = accumulatedBuffer.c_str() + header.length;
                        ssize_t remainingSize = accumulatedBuffer.BuffSize() - header.length;

                        accumulatedBuffer.BuffetClear();
                        accumulatedBuffer.append(remainingData, remainingSize);
                    } else {
                        accumulatedBuffer.BuffetClear();  // 没有剩余数据，清空缓冲区
                    }
                } else {
                    // 数据不完整，等待更多数据
                    break;
                }
            }
        } else if (size == 0) {
            qDebug() << "Peer closed connection";
            break;
        }
    }
}

// 修改 handleEvent() 函数
void ReceiveData::handleEvent(Buffer &buffe)
{
    CloudDrive::Packet ptk;
    std::string str = buffe.returnBuffData();
    std::vector<uint8_t> data(str.begin(), str.end());
    CloudDrive::deserialize(data, ptk);

    if(buffe.BuffSize() == -1) return;

    // 确保只处理完整数据包（由调用者保证）
    if(ptk.header.length != (uint32_t)buffe.BuffSize()) {
        qDebug() << "数据包长度不匹配，期望:" << ptk.header.length << "实际:" << buffe.BuffSize();
        return;
    }

    // 返回的任务事件
    switch (ptk.header.type) {
        // 注册
    case CloudDrive::MessageType::REGISTER: {
        qDebug()<<"ffaf";
        CloudDrive::MesBack msg;
        std::memcpy(&msg, ptk.body.data(), sizeof(CloudDrive::MesBack));
        emit RegistSignal(msg.type);
        break;
    }
    //登录
    case CloudDrive::MessageType::LOGIN: {
        CloudDrive::MesBack msg;
        std::memcpy(&msg, ptk.body.data(), sizeof(CloudDrive::MesBack));
        emit LoginSignal(msg.type);
        break;
    }
    // 刷新
    case CloudDrive::MessageType::REFRESH_FRIEND:{
        CloudDrive::MesBack msg;
        if(msg.type == CloudDrive::MessageReturn::REGISTER_NO) return;
        std::memcpy(&msg,ptk.body.data(),sizeof (CloudDrive::MesBack));
        std::lock_guard<std::mutex> lock(friendMutex);
        for(int i =0;i<static_cast<int32_t>(msg.firendCount);i++){
            FriendList.append(QString::fromStdString(std::to_string(msg.friends[i].id)));
        }
        emit RefreshSignal(FriendList);
        FriendList.clear();
        break;
    }
    // 添加好友相关
    case CloudDrive::MessageType::ADD_FRIEND:{
        CloudDrive::UserInfo uInfo;
        std::memcpy(&uInfo,ptk.body.data(),sizeof (CloudDrive::MesBack));
        emit AddFriendSignal(uInfo.type);
        break;
    }
//    添加好友回复请求
    case CloudDrive::MessageType::ADD_FRIEND_REQ:{
        CloudDrive::UserInfo uIfo;
        std::memcpy(&uIfo,ptk.body.data(),sizeof (CloudDrive::UserInfo));
        std::string userName = uIfo.account;
        emit CallBackFriendSignael(userName);
        break;
    }
//    删除好友
    case CloudDrive::MessageType::REMOVE_FRIEND:{
        CloudDrive::UserInfo uIfo;
        std::memcpy(&uIfo,ptk.body.data(),sizeof (CloudDrive::UserInfo));
        emit RemeveFriend(uIfo.type);
        break;
    }
//      删除好友回复请求
    case CloudDrive::MessageType::REMOVE_FRIEND_REQ:{
        CloudDrive::UserInfo uIfo;
        std::memcpy(&uIfo,ptk.body.data(),sizeof (CloudDrive::UserInfo));
        qDebug()<<uIfo.account;
        emit RemeveFriendREQ(uIfo.type,uIfo.account);
        break;
    }
    // 发送消息
    case CloudDrive::MessageType::SEND_FRIEND_MSG:{
        CloudDrive::UserInfoMsg userMsg;
        std::memcpy(&userMsg,ptk.body.data(),sizeof (CloudDrive::UserInfoMsg));
        emit SendMsgShow(userMsg.account,userMsg.msg);
        break;
    }
    // 刷新文件页面
    case CloudDrive::MessageType::REFRESH_FILELIST:{
        CloudDrive::MesBackFile fileListInfo;
        std::memcpy(&fileListInfo,ptk.body.data(),sizeof (CloudDrive::MesBackFile));
        emit RefreshFileSignal(fileListInfo);
        break;
    }
    //新建文件夹
    case CloudDrive::MessageType::NEWFILEDIR:{
        CloudDrive::MesBack fileReturn;
        std::memcpy(&fileReturn,ptk.body.data(),sizeof (CloudDrive::MesBack));
        emit CreatNewFileSignal(fileReturn.type);
        break;
    }
    //删除文件
    case CloudDrive::MessageType::DELETEFILE:{
        CloudDrive::MesBack fileReturn;
        std::memcpy(&fileReturn,ptk.body.data(),sizeof (CloudDrive::MesBack));
        emit DeleteFileSignal(fileReturn.type);
        break;
    }
        //消息重传
    case CloudDrive::MessageType::UPLOADFILE_ACK:{
        CloudDrive::FileInfo fileInfo;
        std::memcpy(&fileInfo,ptk.body.data(),sizeof (CloudDrive::FileInfo));
        emit FileACKMsg(fileInfo);
        break;
    }
    case CloudDrive::MessageType::DOWNFILE:{
        emit DownFile(ptk.body);
        break;
    }

    default:{
        break;
    }
    }
}

